<template>
  <div class="rule-box">
    <div v-if="$route.query.name" class="back-title">
      <i class="el-icon-arrow-left" @click="$router.go(-1)">返回</i>
    </div>
    <el-form ref="formRef" :model="form">
      <update-step1
        ref="step1Ref"
        :title="newTitle"
        :form="form.ruleEntity"
      />
      <update-step2
        ref="step2Ref"
        :title="newTitle"
        :analyse-type="form.analyseType"
        :form="form2"
      />
      <update-step3 v-if="form.analyseType == 'batch'" ref="step3Ref" :form="form3" />
    </el-form>
    <div class="footer">
      <el-button type="primary" @click="submitForm">保 存</el-button>
      <el-button @click="reset">取 消</el-button>

    </div>

  </div>

</template>

<script>
import updateStep1 from './updateStep1.vue'
import updateStep2 from './updateStep2.vue'
import updateStep3 from './updateStep3.vue'
import formMock from '../mock/form'
import {
  addEntity,
  findRuleById,
  updateEntity,
  queryByEntityType,
  findALlOperator,
  findALlRefData,
  behaviorType,
  getMetricsLists,
  baselines
} from '@/api/icp/labelClassDisplay'
import { changeAction } from '../utils/rule'

export default {
  name: 'EditDialog',
  components: { updateStep1, updateStep2, updateStep3 },
  beforeRouteLeave(to, from, next) {
    to.meta.keepAlive = true
    next()
  },
  data() {
    return {
      changeFirst: false,
      newTitle: this.newTitle,
      // 是否打开
      open: false,
      // 到第几步
      active: undefined,
      //  整个form表单
      form: formMock.form,

      // 是否是在选标签方式
      showLabel: false,
      switchArr: [
        { name: '批量分析', analyseType: 'batch' }, // 批量分析
        { name: '实时分析', analyseType: 'stream' }, // 实时分析
        { name: '序列分析', analyseType: 'cep' } // 序列分析
      ]
    }
  },
  computed: {
    // 传递给步骤1的值
    form1() {
      return this.form.ruleEntity
    },
    // 传递给步骤2的值
    form2() {
      return this.form
    },
    // 传递给步骤3的值
    form3() {
      return this.form.cron
    }
  },
  watch: {
    // 'form.rule.labelType': {
    //   handler(newValue, oldValue) {
    //     // 修改值变换
    //     if (
    //       newValue &&
    //       oldValue &&
    //       newValue !== oldValue &&
    //       this.title === '编辑' &&
    //       this.form.rule.action.conditions.length > 0
    //     ) {
    //       // this.$message.warning('您改变了【标签分类】的值，下一页的【规则】将清空。')
    //       this.form.rule.property = {
    //         conditions: [],
    //         relation: 'and'
    //       }
    //       this.form.rule.action = {
    //         conditions: [],
    //         relation: 'and'
    //       }

    //       this.form.eventDetail.description = ''
    //       this.form.eventDetail.temDesc = ''
    //     }
    //   },
    //   // deep: true,
    //   immediate: true
    // }
  },
  mounted() {
    this.$refs.formRef.scrollTop = 0
    this.getData()
  },
  destroyed() {
    this.form = JSON.parse(JSON.stringify(formMock.form))
  },
  methods: {
    // // 选择选项
    // selectType(data) {
    //   const item = this.form.ruleEntity.dictList.entityTypeList.filter(item => item.value == data)[0]
    //   this.form.rule.labelType = item.id
    //   this.getRuleTables(item.id)
    //
    //   this.changeFirst = true
    // },

    // 提交按钮
    async submitForm() {
      // 先整合form
      // return new Promise((resolve, reject) => {
      //   // 不是序列分析时，只有2步
      //   if (this.form.analyseType !== 'batch') {
      //     this.$refs.step2Ref.submit().then((res) => {
      //       if (res) {
      //         this.form.ref = res.rule.refResource
      //         this.form.ruleEntity.id = this.$router.query.id
      //         this.form = Object.assign({}, this.form, res)
      //         resolve(this.form)
      //       } else {
      //         return false
      //       }
      //     })
      //   } else {
      //     // 序列分析时有3步
      //     this.$refs.step3Ref.submit().then((res) => {
      //       this.form = Object.assign({}, this.form, res)
      //       this.form.ruleEntity.id = this.$router.query.id
      //       resolve(this.form)
      //     })
      //   }
      // }).then(() => {
      //   // 回调发请求
      //   this.form.ruleEntity.analyseType = this.form.analyseType

      //   const ruleContent = { ruleContent: JSON.stringify(this.form) }
      //   if (this.title == '新增') {
      //     addEntity(ruleContent).then((res) => {
      //       this.$message.success('新增成功')
      //       this.open = false
      //       this.$emit('handleAdd')
      //     })
      //   } else {
      //     updateEntity(ruleContent).then((res) => {
      //       this.$message.success('修改成功')
      //       this.open = false
      //       this.$emit('handleAdd')
      //       return
      //     })
      //   }
      // })
      const res1 = await this.$refs.step1Ref.submit()
      const res2 = await this.$refs.step2Ref.submit()
      if (this.form.analyseType === 'batch') {
        const res3 = await this.$refs.step3Ref.submit()
        if (!res3) return
      }
      if (!res1 || !res2) return
      this.form.priority = this.form.eventDetail.priority
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.form.eventDetail.ruleDeclaration = this.form.ruleEntity.ruleDeclaration
          this.form.ruleEntity.analyseType = this.form.analyseType === 'stream' ? 1 : this.form.analyseType === 'batch' ? 2 : 3
          if (!this.$route.query.id) {
            const ruleContent = { ruleContent: JSON.stringify(this.form) }
            addEntity(ruleContent).then((res) => {
              this.$message.success('新增成功')
              this.reset()
            })
          } else {
            this.form.ruleEntity.id = this.$route.query.id
            const ruleContent = { ruleContent: JSON.stringify(this.form) }
            updateEntity(ruleContent).then((res) => {
              this.$message.success('修改成功')
              this.reset()
            })
          }
        }
      })
    },
    // 获取数据
    getData() {
      //  编辑时
      if (this.$route.query.id) {
        findRuleById(this.$route.query.id).then((res) => {
          this.form = res.icpContent ? JSON.parse(res.icpContent) : JSON.parse(res.ruleContent)
          this.$set(this.form, 'ruleEntity.ruleDeclaration', this.form.eventDetail.ruleDeclaration)
          this.getEntityList()
          this.getRuleTables('host')
        })
      } else {
        this.form = {
          ...JSON.parse(JSON.stringify(formMock.form)),
          analyseType: this.$route.query.analyseType ? this.$route.query.analyseType : 'stream'
        }
        // 新增时
        this.getEntityList()
        this.getRuleTables('host')
      }
    },
    getEntityList() {
      // 获取第一步的列表
      // 获取规则分类一级目录
      // entityTree().then((res) => {
      //   this.form.ruleEntity.dictList.entityTypeList = res.map((item) => {
      //     return {
      //       id: item.id,
      //       value: item.name,
      //       label: item.aliasName,
      //       children: item.children
      //     }
      //   })
      //   this.form.rule.transferArray.entity_type = res.map((item) => {
      //     return {
      //       children: item.children,
      //       id: item.name,
      //       labelLevel: 'entityType',
      //       sort: item.sort,
      //       title: item.aliasName
      //     }
      //   })
      // })
      // 获取事件列表
      getMetricsLists().then((res) => {
        this.form.ruleEntity.dictList.metricsList = res.map((item) => {
          return {
            value: item.metricsCode,
            label: item.metricsCode + ' - ' + item.metricsName
          }
        })
      })
    },
    // // 获取规则部分列表
    getRuleTables(data) {
      // 获取属性第一个列表
      queryByEntityType(data).then((res) => {
        this.form.rule.transferArray.attrList = res.map((item) => {
          return {
            name: item.propertyDesc,
            value: item.fieldName,
            label: item.propertyDesc,
            propId: item.id,
            type: item.fieldType,
            isEnum: item.enumStatus,
            enumList: item.dictList
          }
        })
      })

      // 获取实体行为的行为列表
      behaviorType(data).then((res) => {
        this.form.rule.transferArray.actionList = res.map((item) => {
          return {
            value: item.id,
            label: item.fieldAlias,
            children: item.children?.length > 0 ? item.children.map((o) => {
              return {
                value: o.id,
                label: o.fieldAlias,
                behaviorFields: o.behaviorFields
              }
            }) : null
          }
        })
      })
      // 获取所有运算符
      findALlOperator().then((res) => {
        this.form.rule.transferArray.typeOptions = res.map((item) => {
          return {
            value: item.operator,
            label: item.name,
            type: item.type,
            id: item.id,
            isEnum: item.isEnum
          }
        })
        this.form.rule.transferArray.secOperateList = this.form.rule.transferArray.typeOptions.filter((item) => {
          return item.type === 'anumeric'
        })
      })
      // 关联资源表
      findALlRefData().then((res) => {
        this.form.rule.transferArray.resourceList = res.map((item) => {
          return {
            value: item.id,
            label: item.itemName
          }
        })
      })
      if (this.$route.query.id) {
        this.form.rule.action.conditions.forEach((item, index) => {
          if (item.event) {
            changeAction(item.event, index, this.form.rule.transferArray, this.form.analyseType)
          }
        })
      }
      // 获取基线列表
      baselines().then(res=>{
        this.form.rule.transferArray.baselines=res.map(i=>{
          return {
            value:i.baselineType,
            label:i.baselineName
          }
        })
      })
    },
    // 取消
    reset() {
      this.$router.go(-1)
    }

  }

}
</script>

<style lang="scss" scoped>
#app.dark-theme .rule-box {
  background: transparent;

  .in-block {
    color: #fff;
    background: rgba(59, 139, 255, 0.10);
  }
}

.rule-box {
  position: relative;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  background: #eef0f5;

  .in-block {
    background: #fff;
    padding: 20px;

    &::v-deep {
      .title {
        font-weight: 700;
        font-size: 20px;
        margin-bottom: 10px;
      }
    }

    & + .in-block {
      margin-top: 20px;
    }
  }
}

.el-form {
  flex: 1;
  overflow: auto;
}

.footer {
  width: 100%;
  bottom: 0;
  right: 0px;
  padding: 10px 20px;
  text-align: right;
  background: #fff;
  margin-top: 20px;
}
</style>
